import os
import django_excel as excel
from django.contrib.auth.hashers import make_password
from django.views.generic.base import View
from django.shortcuts import render
from django.db.models import Q
from django.http import JsonResponse
from django.conf import settings
from pure_pagination import Paginator, PageNotAnInteger
from utils.mixin_utils import LoginRequiredMixin
from utils.form_utils import get_form_errors
from utils.DataPermissionsFilter import filter_queryset
from systems.models import UserProfile, Role
from systems.forms import UserProfileForm
from systems.views.dept import get_dept_tree, get_dept_tree2


class ListView(LoginRequiredMixin, View):
    def get(self, request):
        v_search = request.GET.get('search')
        if v_search:
            v_search = v_search.strip()
            v_objs = UserProfile.objects.filter(Q(username__icontains=v_search) | Q(name__icontains=v_search) |
                                                Q(mobile__icontains=v_search) | Q(email__icontains=v_search) |
                                                Q(dept__name__icontains=v_search) | Q(role__name__icontains=v_search),
                                                is_superuser=0).order_by('-date_joined')  # 排除超级管理员
        else:
            v_objs = UserProfile.objects.filter(is_superuser=0).order_by('-date_joined')  # 排除超级管理员

        # 非超级管理员，排除管理员用户
        if request.user.is_superuser == 0:
            v_objs = v_objs.filter(is_staff=0)

        # 数据权限过滤
        v_objs = filter_queryset(request, v_objs)

        # 分页功能实现
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(v_objs, per_page=settings.PAGE_NUM, request=request)
        p_objs = p.page(page)
        p_start = (int(page) - 1) * settings.PAGE_NUM  # 避免分页后每行数据序号从1开始
        return render(request, 'systems/user_list.html', {'p_objs': p_objs, 'p_start': p_start, 'p_sum': v_objs.count,
                                                          'h_search': v_search})


class AddView(LoginRequiredMixin, View):
    def get(self, request):
        roles = Role.objects.filter(is_delete=0, status=1)
        # 非超级管理员，排除管理员角色
        if request.user.is_superuser == 0:
            roles = roles.filter(is_admin=0)
        return render(request, 'systems/user.html', {'h_depts': get_dept_tree(),
                                                     'h_roles': roles,
                                                     'h_dept_belongs': get_dept_tree2()})

    def post(self, request):
        v_form = UserProfileForm(request.POST)
        if v_form.is_valid():
            new_obj = v_form.save(commit=False)
            new_obj.password = make_password(settings.DEFAULT_PWD)
            new_obj.creator = request.user.name
            new_obj.modifier = request.user.name
            # 数据归属部门不填，则默认为当前创建用户的部门ID
            if new_obj.dept_belong_id is None:
                new_obj.dept_belong_id = request.user.dept_id

            upload_file = request.FILES.get("file", None)
            if upload_file is not None:
                print(upload_file.name)
                fs = open(os.path.join(settings.BASE_DIR, 'statics/images/avatar/' + upload_file.name), 'wb+')
                for chunk in upload_file.chunks():
                    fs.write(chunk)
                fs.close()
                new_obj.avatar = upload_file.name

            new_obj.save()
            v_form.save_m2m()
            return JsonResponse({'code': '200', 'msg': '新增成功'})
        else:
            return JsonResponse({'code': '444', 'msg': get_form_errors(v_form)})


class DetailView(LoginRequiredMixin, View):
    def get(self, request):
        v_obj = UserProfile.objects.get(id=request.GET.get('id'))
        v_user_roles = list(v_obj.role.all())
        v_roles = Role.objects.filter(is_delete=0, status=1)
        # 非超级管理员，排除管理员角色
        if request.user.is_superuser == 0:
            v_roles = v_roles.filter(is_admin=0)
        return render(request, 'systems/user.html', {'h_obj': v_obj,
                                                     'h_depts': get_dept_tree(v_obj.dept.id),
                                                     'h_roles': v_roles,
                                                     'h_user_roles': v_user_roles,
                                                     'h_dept_belongs': get_dept_tree2(v_obj.dept_belong_id)})


class ModifyView(LoginRequiredMixin, View):
    def post(self, request):
        v_obj = UserProfile.objects.get(id=request.POST.get('id'))
        v_form = UserProfileForm(request.POST, instance=v_obj)
        if v_form.is_valid():
            old_obj = v_form.save(commit=False)
            old_obj.modifier = request.user.username
            # 数据归属部门不填，则默认为当前创建用户的部门ID
            if old_obj.dept_belong_id is None:
                old_obj.dept_belong_id = request.user.dept_id

            upload_file = request.FILES.get("file", None)
            if upload_file is not None:
                print(upload_file.name)
                fs = open(os.path.join(settings.BASE_DIR, 'statics/images/avatar/' + upload_file.name), 'wb+')
                for chunk in upload_file.chunks():
                    fs.write(chunk)
                fs.close()
                old_obj.avatar = upload_file.name

            old_obj.save()
            v_form.save_m2m()
            return JsonResponse({'code': '200', 'msg': '修改成功'})
        else:
            return JsonResponse({'code': '444', 'msg': get_form_errors(v_form)})


class DeleteView(LoginRequiredMixin, View):
    def get(self, request, i_id):
        v_user = UserProfile.objects.get(id=i_id)
        if v_user.is_staff == 1 and request.user.is_superuser == 0:
            return JsonResponse({'code': '400', 'msg': '禁止删除管理员'})
        try:
            v_user.delete()
            return JsonResponse({'code': '200', 'msg': '删除成功'})
        except:
            return JsonResponse({'code': '400', 'msg': '该用户已指派任务，禁止删除'})


class ExportView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'systems/user_export.html', {'h_id': request.GET.get('id')})

    def post(self, request):
        v_id = request.POST.get('id')
        if v_id is None or v_id == '':
            return JsonResponse({'code': '400', 'msg': '用户信息为空，请重新尝试'})

        v_start_datetime = request.POST.get('start_datetime')
        v_end_datetime = request.POST.get('end_datetime')
        v_user_name = ""
        v_results = [['用户名', '任务名称', '任务描述', '指派人', '指派时间', '任务状态', '完成时间']]
        v_task_assignments = TaskAssignment.objects.filter(performMan_id=v_id, create_datetime__gte=v_start_datetime,
                                                           create_datetime__lte=v_end_datetime
                                                           ).order_by('-create_datetime')
        for taskAssignment in v_task_assignments:
            v_user_name = taskAssignment.performMan.username
            v_list = [taskAssignment.performMan.username, taskAssignment.task.taskName,
                      taskAssignment.task.taskDesc, taskAssignment.creator, taskAssignment.create_datetime,
                      taskAssignment.taskState, taskAssignment.aEndTime]
            v_results.append(v_list)
        sheet = excel.pe.Sheet(v_results)
        return excel.make_response(sheet, "xlsx", 200,
                                   v_user_name + "的任务完成情况" + v_start_datetime + "至" + v_end_datetime, "任务")
